package com.bookstore.spring.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.Reader;

/**
 * Created by Admin on 2016/9/1.
 */
public class MybatisSessionFactory {
    private static final ThreadLocal<SqlSession> threadLocal=new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactory;

    private static String CONFIG_FILE_LOCATION= "conf.xml";
    private static String configFile=CONFIG_FILE_LOCATION;
    static{
        try{
            Reader reader= Resources.getResourceAsReader(configFile);
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private MybatisSessionFactory(){

    }

    public static SqlSession getSession(){
        SqlSession sqlSession=threadLocal.get();
        if(sqlSession==null){
            if(sqlSessionFactory==null){
                rebuildSessionFactory();
            }
            sqlSession=(sqlSessionFactory!=null)?sqlSessionFactory.openSession():null;
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }

    public static void rebuildSessionFactory() {
        try{
            Reader reader=Resources.getResourceAsReader(configFile);
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void closeSession(){
        SqlSession sqlSession=threadLocal.get();
        threadLocal.set(sqlSession);
        if(sqlSession!=null){
            sqlSession.close();
        }
         threadLocal.remove();
    }

    public static SqlSessionFactory getSessionFactory(){
        return sqlSessionFactory;
    }

    public static void setConfigFile(String configFile){
        MybatisSessionFactory.configFile=configFile;
        sqlSessionFactory=null;
    }

}
